package com.example.sunmiv1.listener;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


// recyclerView加載更多的刷新
public abstract class LoadMoreOnScrollListener extends RecyclerView.OnScrollListener {

    private LinearLayoutManager mLinearLayoutManager;

    private int currentPage = 1;

    /**
     * 已經加載出來的item個數
     */
    private int totalItemCount;

    /**
     * 上一個totalItemCount
     */
    private int previousTotal = 0;

    /**
     * 屏幕上可見item個數
     */
    private int visibleItemCount;

    /**
     * 屏幕可見item的第一個
     */
    private int firstVisiableItem;

    /**
     * 是否正在上拉數據
     */
    private boolean isPulling = true;

    public LoadMoreOnScrollListener(LinearLayoutManager linearLayoutManager) {
        this.mLinearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        // 可見item個數
        visibleItemCount = recyclerView.getChildCount();
        // item總數
        totalItemCount = mLinearLayoutManager.getItemCount();
        // 第一個可見item
        firstVisiableItem = mLinearLayoutManager.findFirstVisibleItemPosition();

        if (isPulling) {
            if (totalItemCount > previousTotal) {
                // 數據成功獲取纔會執行 說明數據已經加載結束
                isPulling = false;
                previousTotal = totalItemCount;
            }
        }

        //如果獲取數據失敗，則不會這行此處，因爲loading始終爲true
        //當最後一個item可見時，執行加載
        if (!isPulling && totalItemCount - visibleItemCount <= firstVisiableItem) {
            currentPage++;
            onLoadMore(currentPage);
            isPulling = true;
        }
        if (visibleItemCount == 0) {
            currentPage++;
            onLoadMore(currentPage);
            isPulling = true;
        }
    }

    public abstract void onLoadMore(int currentPage);
}

